'use strict'

class music {
  constructor() {
    this.param = '/'
  }

  async get(c) {
    let ret = await c.service.psql.query(`select * from music order by music_id asc`)
    c.status(200).send(ret.rows)
  }

  async post(c) {
    var obj = c.body
    console.log(obj)
    if (obj) {
      var { music_singer, music_time, music_url, music_name  } = obj
      let row = await c.service.psql.query(`select * from music order by music_id asc`)
      let music_id = parseInt(row.rows[row.rows.length - 1].music_id) + 1
      console.log(music_id, music_singer, music_time, music_url, music_name)
      let ret = await c.service.psql.query(`insert into music values('${music_id}','${music_singer}', '${music_time}', '${music_url}', '${music_name}')`)
      console.log(ret)
      c.status(200).send('已接收')
    } else {
      c.status(400).send('please check your data :)')
    }
  }

  async delete(c) {
    if (!c.body.isRows) {
      var id = c.body.id
      console.log(id)
      if (id) {
        let ret = await c.service.psql.query(`delete from music where music_id like '${id}'`)
        let ret2 = await c.service.psql.query(`delete from collectmusic where collectmusic_id like '${id}'`)
        console.log(ret, ret2)
        c.send('已删除')

      } else {
        c.send('删除失败')
      }
    } else {
      var idArr = c.body.idArr
      console.log(idArr)
      for (let i = 0; i < idArr.length; i++) {
        let ret = await c.service.psql.query(`delete from music where music_id like '${idArr[i]}'`)
        let ret2 = await c.service.psql.query(`delete from collectmusic where collectmusic_id like '${idArr[i]}'`)
        console.log(ret, ret2)
      }
      c.send('complete')
    }
  }

  async put(c) {
    var req = c.body
    console.log(req)
    if (req.music_singer) {
      let ret = await c.service.psql.query(`update music set music_singer = '${req.music_singer}' where music_id like '${req.music_id}'`)
      console.log('singer', ret)
    }
    if (req.music_time) {
      let ret = await c.service.psql.query(`update music set music_time = '${req.music_time}' where music_id like '${req.music_id}'`)
      console.log('time', ret)
    }
    if (req.music_url) {
      let ret = await c.service.psql.query(`update music set music_url = '${req.music_url}' where music_id like '${req.music_id}'`)
      console.log('url', ret)
    }
    if (req.music_name) {
      let ret = await c.service.psql.query(`update music set music_name = '${req.music_name}' where music_id like '${req.music_id}'`)
      console.log('name', ret)
    }
    c.send('complete')
  }
}

module.exports = music
